import json
import datetime
from typing import Dict, Any, Optional
import logging
from app.core.llm  import call_llm_gemini_image
from prompts.templates import MERCHANT_DECISION_PROMPT
from app.models.schemas import (
    MerchantDecisionRequest,
    MerchantDecisionResponse,
    DecisionResult
)

# 获取日志记录器
logger = logging.getLogger(__name__)

def get_decision(request: MerchantDecisionRequest) -> MerchantDecisionResponse:
    """
    基于评估结果进行决策
    
    Args:
        request: 商家决策请求对象
    
    Returns:
        MerchantDecisionResponse: 商家决策结果
    """
    logger.info(f"开始为商家做决策: {request.evaluation_result.merchant_name}, 决策类型: {request.decision_type}")
    
    eval_result = request.evaluation_result
    
    # 准备决策参数
    decision_params = {
        "merchant_id": eval_result.merchant_id,
        "merchant_name": eval_result.merchant_name,
        "financial_score": eval_result.financial_score.score,
        "financial_level": eval_result.financial_score.level,
        "operational_score": eval_result.operational_score.score,
        "operational_level": eval_result.operational_score.level,
        "risk_score": eval_result.risk_score.score,
        "risk_level": eval_result.risk_score.level,
        "overall_score": eval_result.overall_score.score,
        "overall_level": eval_result.overall_score.level,
        "overall_analysis": eval_result.overall_score.analysis,
        "recommendations": eval_result.recommendations,
        "decision_type": request.decision_type,
        "decision_context": json.dumps(request.decision_context or {}, ensure_ascii=False)
    }
    
    decision_result_json = call_llm_gemini_image(
        MERCHANT_DECISION_PROMPT, 
        decision_params,
        model="google/gemini-2.0-flash-001", 
        return_json=True
    )
    
    try:
        decision_result_data = json.loads(decision_result_json)
        decision_result = DecisionResult(
            decision=decision_result_data["decision"],
            confidence=decision_result_data["confidence"],
            reasons=decision_result_data["reasons"],
            suggestions=decision_result_data.get("suggestions", [])
        )
    except Exception as e:
        logger.error(f"解析决策结果失败: {e}")
        logger.error(f"原始结果: {decision_result_json}")
        decision_result = DecisionResult(
            decision="拒绝",
            confidence=0.5,
            reasons=["决策过程出错"],
            suggestions=["请重新尝试决策"]
        )
    
    # 构建决策响应
    decision_response = MerchantDecisionResponse(
        merchant_id=eval_result.merchant_id,
        merchant_name=eval_result.merchant_name,
        decision_result=decision_result,
        decision_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    
    logger.info(f"商家决策完成: {eval_result.merchant_name}, 决策结果: {decision_result.decision}")
    return decision_response 